package com.zhang.controller.brand;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.brand.entity.Brand;
import com.zhang.brand.entity.BrandCategory;
import com.zhang.brand.service.IBrandCategoryService;
import com.zhang.brand.service.IBrandService;
import com.zhang.common.util.result.R;
import com.zhang.common.util.result.RUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 品牌表 前端控制器
 * </p>
 *
 * @author 创世神
 * @since 2023-08-27
 */
@RestController
@RequestMapping("/brand/")
@Slf4j
public class BrandController {
    @Autowired
    private IBrandService brandService;
    @Autowired
    private IBrandCategoryService brandCategoryService;

    @PostMapping("add")
    R addBrand(@RequestBody Brand brand) {
        brandService.save(brand);
        return RUtils.successMsg("新增成功");
    }

    @GetMapping("getToPage/{pageNum}/{pageSize}")
    R getToPage(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        Page<Brand> page = brandService.getToPage(pageNum, pageSize);
        return RUtils.successData(page);
    }

    @GetMapping("getbyid/{brandId}")
    public R getBrandById(@PathVariable String brandId) {
        Brand byId = brandService.getById(brandId);
        return RUtils.successData(byId);
    }
    @GetMapping("list/byCategory")
    R getBrandListByCategoryId(String categoryId){
       List<Brand> brands= brandService.getByCategoryId(categoryId);
       return RUtils.successData(brands);
    }

    @PutMapping("modify")
    R modifyBrand(@RequestBody Brand brand) {
        log.info("进入方法");
        brandService.updateById(brand);
        return RUtils.successMsg("修改成功");
    }

    @DeleteMapping("del/{brandId}")
    R deleteBrand(@PathVariable Long brandId) {
        boolean b = brandService.removeById(brandId);
        QueryWrapper<BrandCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("brand_id", brandId);
        /*删除关联表*/
        brandCategoryService.remove(wrapper);
        return b ? RUtils.successMsg("删除成功") : RUtils.err("删除失败");
    }
}
